package util

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
	"wx-mp-push-demo/conf"
	"wx-mp-push-demo/entity"
)

// 获取AccessToken
func getAccessToken() string {
	url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
		"&appid=" + conf.Config.WxAppId +
		"&secret=" + conf.Config.WxAppSecret

	fmt.Println("url : ", url)
	httpResp, _ := http.Get(url)

	var accessTokenResp struct {
		AccessToken string `json:"access_token"`
		ExpiresIn   int    `json:"expires_in"`
	}

	bodyData, _ := ioutil.ReadAll(httpResp.Body)
	_ = json.Unmarshal(bodyData, &accessTokenResp)

	return accessTokenResp.AccessToken
}

// 向所有关注了公众号的用户推送消息
func PostWxMpTempMessageToAll() {
	url := "https://api.weixin.qq.com/cgi-bin/message/template/send?" +
		"access_token=" + getAccessToken()

	fmt.Println("url : ", url)

	userList := getUserList()
	for _, openid := range userList {
		msg := getMessage(openid)

		jsonMsg, _ := json.Marshal(msg)

		httpResp, _ := http.Post(url, conf.CONTENT_TYPE, bytes.NewReader(jsonMsg))

		bodyData, _ := ioutil.ReadAll(httpResp.Body)

		fmt.Println(string(bodyData))
	}
}

// 获取所有关注了公众号的用户openid
func getUserList() []string {
	url := "https://api.weixin.qq.com/cgi-bin/user/get?" +
		"access_token=" + getAccessToken()

	fmt.Println("url : ", url)

	httpResp, _ := http.Get(url)
	bodyData, _ := ioutil.ReadAll(httpResp.Body)

	var resp struct {
		Total      int    `json:"total"`
		Count      int    `json:"count"`
		NextOpenid string `json:"next_openid"`
		Data       struct {
			Openid []string `json:"openid"`
		}
	}

	_ = json.Unmarshal(bodyData, &resp)

	return resp.Data.Openid
}

// 生成一条模板消息
func getMessage(openid string) entity.WxMpMessagePubTemp {
	msg := entity.WxMpMessagePubTemp{
		ToUser:     openid,
		TemplateId: conf.Config.WxTemplateId,
		Url:        "https://gitee.com/chentong001/wx-mp-push-demo-go",
	}

	msg.Data.Date = entity.DataType{
		// 格式化时间为 yyyy-MM-dd
		Value: time.Now().Format("2006-01-02"),
		Color: "#3CB371",
	}

	msg.Data.Region = entity.DataType{
		Value: conf.Config.WeatherCity,
		Color: "#228B22",
	}

	weather := getWeather(conf.Config.WeatherCity)

	msg.Data.Temp = entity.DataType{
		Value: "最高温：" + weather.TemDay + "℃" + " 最低温：" + weather.TemDay + "℃",
		Color: "#FF00FF",
	}

	msg.Data.Weather = entity.DataType{
		Value: weather.Wea,
		Color: "#4169E1",
	}

	msg.Data.Wind = entity.DataType{
		Value: weather.Win + weather.WinSpeed + " " + weather.WinMeter,
		Color: "#FFD700",
	}

	msg.Data.Remark = entity.DataType{
		Value: "点击访问我的gitee仓库！",
		Color: "#3399CC",
	}

	return msg
}

// 获取天气接口
func getWeather(city string) *entity.Weather {
	url := "https://www.yiketianqi.com/free/day?" +
		"appid=" + conf.Config.WeatherAppId +
		"&appsecret=" + conf.Config.WeatherAppSecret +
		"&city=" + city +
		"&unescape=1"

	fmt.Println("url : ", url)

	httpResp, _ := http.Get(url)
	bodyData, _ := ioutil.ReadAll(httpResp.Body)

	var weather entity.Weather
	_ = json.Unmarshal(bodyData, &weather)

	return &weather
}
